#include "Stdafx.h"
#include "HttpContext.h"

#include "poco/Event.h"
#include "poco/Net/HTTPServerRequest.h"
#include "poco/Net/HTTPServerResponse.h"

#include "HttpRequest.h"
#include "HttpResponse.h"

namespace MiniHttpServer
{
	HttpContextHandler::HttpContextHandler( Poco::Event & ev ) : m_event(ev)
	{

	}

	HttpContextHandler::~HttpContextHandler()
	{
		m_event.set();
	}


	HttpContext::HttpContext( Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response, std::shared_ptr<HttpContextHandler> const& pContext ) 
		: m_request(gcnew HttpRequest(request))
		, m_response(gcnew HttpResponse(response))
		, m_ppContextHandler(new std::shared_ptr<HttpContextHandler>(pContext))
	{

	}

	HttpContext::~HttpContext()
	{
		this->!HttpContext();
	}

	HttpContext::!HttpContext()
	{
		delete m_request; m_request = nullptr;
		delete m_response; m_response = nullptr;
		delete m_ppContextHandler; m_ppContextHandler = nullptr;
	}

	void HttpContext::Close()
	{
		if(m_request->HasBody)
		{
			const int bfrSz = 1024*4;
			array<unsigned char>^ bfr = gcnew array<unsigned char>(bfrSz);
			System::IO::Stream^ stream = m_request->GetBody();
			// make sure the request body buffer is empty
			int rd = bfrSz;
			while(rd == bfrSz)
			{
				rd = stream->Read(bfr,0,bfrSz);
			};
		}

		delete m_request; m_request = nullptr;
		delete m_response; m_response = nullptr;
		delete m_ppContextHandler; m_ppContextHandler = nullptr;
	}

};
